import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/launch_util.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/open_page_util.dart';
import 'package:gzmall_app/common/setting_util.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/model/advertisement.dart';
import 'package:gzmall_app/model/deposit_preferences.dart';
import 'package:gzmall_app/model/user.dart';
import 'package:gzmall_app/model/wechat_pay_info.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:tobias/tobias.dart' as tobias;

class TopupPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return TopupPageState();
  }
}

class TopupPageState extends State<TopupPage> {
  String _money;
  List<DepositPreferences> _depositPreferences = [];
  List<Advertisement> _advertisements = [];
  String _depositId;

  TextEditingController _moneyController = TextEditingController();

  @override
  void initState() {
    super.initState();
    fluwx.registerWxApi(appId: Api.wxAppId);
    fluwx.weChatResponseEventHandler.listen((data) {
      if (data is fluwx.WeChatPaymentResponse) {
        print("<fluwx> fluwx.weChatResponseEventHandler.listen");
        print("<fluwx> data.type " + data.type.toString());
        print("<fluwx> data.errCode " + data.errCode.toString());
        print("<fluwx> data.extData " + data.extData.toString());

        if (data != null && data.errCode != null) {
          switch (data.errCode) {
            case 0:
              // 成功 展示成功页面
              _paySuccess();
              break;
            case -1:
              // 错误 可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。
              ToastUtil.showMessageToast(data.errStr ?? "微信支付错误");
              break;
            case -2:
              // 用户取消 无需处理。发生场景：用户不支付了，点击取消，返回APP。
              break;
          }
        }
      }
    });

    _getData();
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    List<Widget> _dpWidgets = [];
    if (_depositPreferences != null && _depositPreferences.length > 0) {
      _dpWidgets = _depositPreferences.map((v) {
        return _createReturnItem(v);
      }).toList();
    }
    return Scaffold(
        appBar: _createAppBar(),
        body: ListView(children: <Widget>[
          InkWell(
            onTap: () {
              if (_advertisements != null && _advertisements.length > 0) {
                Advertisement adv = _advertisements[0];
                OpenPageUtil.openPage(
                    context, adv?.pageType, adv?.pageUrl, adv?.params,
                    name: adv?.name, uid: _user?.id?.toString());
              }
            },
            child: _advertisements != null && _advertisements.length > 0
                ? CachedNetworkImage(
                    imageUrl: _advertisements[0].image,
                    width: double.infinity,
                    height: width / 2,
                    fit: BoxFit.fill,
                  )
                : Container(
                    width: double.infinity,
                    height: width / 2,
                    color: Colors.grey,
                  ),
          ),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.only(top: 23.0, bottom: 18.0),
            child: Column(
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.only(bottom: 15.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        "您的当前余额为",
                        style: TextStyle(
                            fontSize: 13.0, color: ColorCommon.grey11),
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 15.0),
                        child: Text(
                          "${_user?.moneybag ?? "0.0"}",
                          style: TextStyle(
                              fontSize: 17.0, color: ColorCommon.primaryColor),
                        ),
                      ),
                      Text(
                        "元",
                        style: TextStyle(
                            fontSize: 17.0, color: ColorCommon.grey11),
                      ),
                    ],
                  ),
                ),
                _createInputMoney(),
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.only(top: 10.0),
            color: Colors.white,
            padding:
                const EdgeInsets.symmetric(horizontal: 25.0, vertical: 25.0),
            child: Wrap(
              spacing: 14.0,
              runSpacing: 14.0,
              children: _dpWidgets,
            ),
          ),
          Container(
            color: Colors.white,
            height: 2.0,
            padding: const EdgeInsets.symmetric(horizontal: 20.0),
            child: Container(
              height: 2.0,
              color: ColorCommon.primaryColor,
            ),
          ),
          Container(
            padding: const EdgeInsets.all(20.0),
            color: Colors.white,
            child: Text(
              "温馨提示: 充值只可用与平台消费,暂不提供提现功能。给您带来的不便,敬请谅解",
              style: TextStyle(fontSize: 16.0, color: ColorCommon.primaryColor),
            ),
          ),
        ]));
  }

  _createAppBar() {
    return AppBar(
      elevation: 0.0,
      title: Text("充值返现"),
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      actions: <Widget>[
        InkWell(
          onTap: () {
            Navigator.of(context).pushNamed('/topup_record_page');
          },
          child: Container(
            child: Text("明细"),
            alignment: Alignment.center,
            padding: const EdgeInsets.only(right: 15.0),
          ),
        ),
      ],
    );
  }

  _createInputMoney() {
    return Container(
        height: 45.0,
        margin: const EdgeInsets.symmetric(horizontal: 30.0),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                height: double.infinity,
                alignment: Alignment.centerLeft,
                decoration: BoxDecoration(
                    color: ColorCommon.grey2,
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(50.0),
                        bottomLeft: Radius.circular(50.0))),
                child: TextField(
                  textAlign: TextAlign.center,
                  controller: _moneyController,
                  style: TextStyle(color: ColorCommon.black1),
                  decoration: InputDecoration.collapsed(
                    hintText: "请输入金额进入充值操作",
                    hintStyle:
                        TextStyle(fontSize: 14.0, color: ColorCommon.grey11),
                  ),
                  onChanged: (str) {
                    _money = str ?? '';
                  },
                ),
              ),
            ),
            InkWell(
              onTap: () {
                if (_money != null && _money.isNotEmpty) {
                  _postDeposits(_money);
                } else {
                  ToastUtil.showMessageToast("请输入金额进入充值操作");
                }
              },
              child: Container(
                  width: 85.0,
                  height: double.infinity,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Colors.red,
                      borderRadius: BorderRadius.only(
                          topRight: Radius.circular(50.0),
                          bottomRight: Radius.circular(50.0))),
                  child: Text(
                    "充值",
                    style: TextStyle(color: Colors.white, fontSize: 14.0),
                  )),
            ),
          ],
        ));
  }

  Widget _createReturnItem(DepositPreferences dp) {
    double width = MediaQuery.of(context).size.width;
    return InkWell(
      onTap: () {
        if (dp.fullMoney != null && dp.fullMoney.isNotEmpty) {
          _postDeposits(dp.fullMoney);
        } else {
          ToastUtil.showMessageToast("充值金额异常");
        }
      },
      child: Container(
        width: (width - 25 - 25 - 14 - 14) / 3,
        height: 75.0,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: ColorCommon.primaryColor,
          borderRadius: BorderRadius.all(Radius.circular(5.0)),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "满${dp.fullMoney ?? "0.0"}送",
              style: TextStyle(color: Colors.white, fontSize: 15.0),
            ),
            Container(
              color: Colors.white,
              height: 2.0,
              margin:
                  const EdgeInsets.symmetric(horizontal: 10.0, vertical: 4.0),
            ),
            Text(
              "${dp.bonus ?? "0.0"}",
              style: TextStyle(color: Colors.white, fontSize: 15.0),
            ),
          ],
        ),
      ),
    );
  }

  _showPayWay(BuildContext context, String money) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(15.0),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Stack(
                alignment: FractionalOffset(0.98, 0.5),
                children: <Widget>[
                  Container(
                    width: double.infinity,
                    alignment: Alignment.center,
                    child: Text(
                      "确认付款",
                      textAlign: TextAlign.center,
                      style:
                          TextStyle(fontSize: 16.0, color: ColorCommon.black1),
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      Navigator.of(context).pop(false);
                    },
                    child: Text(
                      "取消",
                      style:
                          TextStyle(fontSize: 16.0, color: ColorCommon.black1),
                    ),
                  ),
                ],
              ),
              Align(
                alignment: Alignment.center,
                child: Padding(
                  padding: const EdgeInsets.only(top: 20.0, bottom: 20.0),
                  child: Text(
                    "¥ " + (money != null ? money.toString() : "0.0"),
                    style: TextStyle(
                      fontSize: 36.0,
                      color: ColorCommon.primaryColor,
                    ),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(bottom: 10.0),
                child: Text(
                  "付款方式",
                  style: TextStyle(fontSize: 15.0, color: ColorCommon.black1),
                ),
              ),
              Expanded(
                child: ListView(
                  padding: const EdgeInsets.only(top: 0.0),
                  children: <Widget>[
                    LaunchUtil.isInstallWeixin && !SettingUtil.isAppStoreAudit()
                        ? InkWell(
                            onTap: () {
                              if (_depositId != null && _depositId.isNotEmpty) {
                                _getPayInfo(_depositId, "wepay");
                              } else {
                                ToastUtil.showMessageToast("下单错误, 请重试");
                                Navigator.of(context).pop(true);
                              }
                            },
                            child: Container(
                              color: ColorCommon.grey5,
                              padding: const EdgeInsets.only(
                                  left: 15.0,
                                  right: 15.0,
                                  bottom: 10.0,
                                  top: 10.0),
                              margin: const EdgeInsets.only(bottom: 10.0),
                              child: Row(children: <Widget>[
                                Image.asset(
                                  "images/wechat.png",
                                  width: 30.0,
                                  height: 30.0,
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(
                                      left: 10.0, right: 10.0),
                                  child: Text(
                                    "微信支付",
                                    style: TextStyle(
                                        fontSize: 15.0,
                                        color: ColorCommon.black1),
                                  ),
                                )
                              ]),
                            ),
                          )
                        : Container(),
                    LaunchUtil.isInstallAlipay && !SettingUtil.isAppStoreAudit()
                        ? InkWell(
                            onTap: () {
                              if (_depositId != null && _depositId.isNotEmpty) {
                                _getPayInfo(_depositId, "alipay");
                              } else {
                                ToastUtil.showMessageToast("下单错误, 请重试");
                                Navigator.of(context).pop(true);
                              }
                            },
                            child: Container(
                              color: ColorCommon.grey5,
                              padding: const EdgeInsets.only(
                                  left: 15.0,
                                  right: 15.0,
                                  bottom: 10.0,
                                  top: 10.0),
                              margin: const EdgeInsets.only(bottom: 10.0),
                              child: Row(children: <Widget>[
                                Image.asset(
                                  "images/alipay.png",
                                  width: 30.0,
                                  height: 30.0,
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(
                                      left: 10.0, right: 10.0),
                                  child: Text(
                                    "支付宝",
                                    style: TextStyle(
                                        fontSize: 15.0,
                                        color: ColorCommon.black1),
                                  ),
                                ),
                              ]),
                            ),
                          )
                        : Container()
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  _paySuccess() {
    setState(() {
      _money = "";
      _depositId = "";
    });
    Navigator.of(context).pop(true);
    Navigator.of(context).pushNamed('/topup_record_page').then((value) {
      _getData();
    });
  }

  _getDepositPreferences() {
    NetUtil.get(
        context,
        Api.depositPreferences,
        (data, message) {
          if (!mounted) return;
          setState(() {
            _depositPreferences = (data as List)
                ?.map((e) => e == null ? null : DepositPreferences.fromJson(e))
                ?.toList();
          });
        },
        isInterceptError: false,
        errorCallBack: (e) {
          if (!mounted) return;
        });
  }

  _getData() {
    _getAdvertisements();
    _getUserInfoFromLocate();
    _getDepositPreferences();
  }

  _getAdvertisements() {
    Map<String, String> params = {"page_name": "topup_page"};

    NetUtil.get(context, Api.advertisements, (data, message) {
      if (!mounted) return;
      setState(() {
        _advertisements = (data as List)
            ?.map((e) => e == null ? null : Advertisement.fromJson(e))
            ?.toList();
      });
    }, params: params, errorCallBack: (e) {});
  }

  _postDeposits(String money) {
    FormData formData = new FormData.fromMap({"deposit[money]": money});

    NetUtil.post(context, Api.deposits, (data, message) {
      _depositId = data["id"].toString();
      _showPayWay(context, money);
    }, params: formData, isShowLoading: true);
  }

  _getPayInfo(String depositId, String payMethod) async {
    FormData formData = new FormData.fromMap(
        {"deposit_id": depositId, "pay_method": payMethod});

    NetUtil.post(context, Api.depositsPay, (data, message) {
      ToastUtil.showMessageToast(message);

      if (payMethod == "wepay") {
        // 微信支付
        WechatPayInfo wechatPayInfo = WechatPayInfo.fromJson(data);
        fluwx
            .payWithWeChat(
                appId: wechatPayInfo.appid,
                partnerId: wechatPayInfo.partnerid,
                prepayId: wechatPayInfo.prepayid,
                packageValue: wechatPayInfo.package,
                nonceStr: wechatPayInfo.noncestr,
                timeStamp: int.parse(wechatPayInfo.timestamp),
                sign: wechatPayInfo.sign)
            .then((value) {
          print("<fluwx> then(value) ${value}");
        });
      } else if (payMethod == "alipay") {
        // 支付宝支付
        _callAlipay(data);
      }
    }, params: formData, isShowLoading: true);
  }

  _callAlipay(String payInfo) async {
    Map payResult = {};
    try {
      payResult = await tobias.aliPay(payInfo);
      print("<tobias> $payResult");
      if (payResult != null && payResult["resultStatus"] != null) {
        switch (payResult["resultStatus"].toString()) {
          case "9000":
            // 订单支付成功
            _paySuccess();
            break;
          case "6001":
            // 用户中途取消
            break;
          default:
            // 支付失败
            ToastUtil.showMessageToast(payResult["memo"]);
            break;
        }
      }
    } on Exception catch (e) {
      print("<tobias> $e");
    }
  }

  User _user = User.empty();
  _getUserInfoFromLocate() async {
    await _user.getUserInfo();
    if (_user.id > 0 && _user.authToken != null && _user.authToken.isNotEmpty) {
      _getUserInfoFromNet(_user.id);
    } else {
      Navigator.of(context).pushNamed('/login_page');
    }
  }

  _getUserInfoFromNet(int id) {
    NetUtil.get(
        context,
        Api.users + id.toString(),
        (data, message) {
          if (!mounted) return;
          setState(() {
            String _authToken = _user.authToken;
            _user = User.fromJson(data);
            _user.authToken = _authToken;
            User.saveUserInfo(_user);
          });
        },
        isInterceptError: false,
        errorCallBack: (e) {
          if (!mounted) return;
        });
  }
}
